package org.sample.commons.lang;

import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 消息摘要工具类
 */
public class HashUtils {

    private static final Logger log = LoggerFactory.getLogger(HashUtils.class);

    public static String hashpw(String message) {
        return BCrypt.hashpw(message, BCrypt.gensalt(ThreadLocalRandom.current()));
    }

    public static boolean checkpw(String message, String hashMessage) {
        return BCrypt.checkpw(message, hashMessage);
    }

    public static String md5(String message) {
        return encode(message, Algorithm.MD5);
    }

    public static String sha1(String message) {
        return encode(message, Algorithm.SHA1);
    }

    public static String encode(String message, Algorithm algorithm) {
        if (algorithm == Algorithm.BCrypt)
            return hashpw(message);
        try {
            MessageDigest instance = MessageDigest.getInstance(algorithm.value);
            byte[] bytes = instance.digest(message.getBytes(StandardCharsets.UTF_8));
            return byte2Hex(bytes);
        } catch (Exception e) {
            log.warn("编码失败", e);
            return null;
        }
    }

    public static String byte2Hex(byte[] bytes) {
        StringBuilder result = new StringBuilder(32);
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0XFF);
            if (hex.length() == 1)
                result.append("0");
            result.append(hex);
        }
        return result.toString();
    }

    public enum Algorithm {
        MD5("MD5"),
        SHA1("SHA-1"),
        SHA256("SHA-256"),
        SHA512("SHA-512"),
        BCrypt("BCrypt");

        String value;

        Algorithm(String value) {
            this.value = value;
        }
    }
}  